extends Node


const MapScn = preload("res://Map.tscn")
const Map = preload("res://Map.gd")


onready var n_gene_data = $GenerateData



func _ready():
	# 添加地图
	var map_data = {}
	var index = 0
	for pos in n_gene_data.get_map_pos_list():
		# 添加地图节点
		var map := MapScn.instance() as Map
		map.set_map_pos(pos)
		map.position = Vector2(5000 * index, -10000)
		self.add_child(map)
		# 记录数据
		map_data[pos] = map
		index += 1
	
	# 连接地图
	var directions = [Vector2.LEFT, Vector2.RIGHT, Vector2.UP, Vector2.DOWN]
	for pos in n_gene_data.get_map_pos_list():
		var curr_map := map_data[pos] as Map
		# 周围有地图则进行连接
		var next : Vector2
		for dir in directions:
			next = pos + dir
			if map_data.has(next):
				var map := map_data[next] as Map
				curr_map.connect_map(map, next)
	
	# 连接信号
	for pos in map_data.keys():
		var map := map_data[pos] as Map
		if map.connect("entered_map", self, "_on_Map_entered_map", [pos]) != OK:
			printerr(map, "在连接 entered_map 信号时出现错误")
		if map.connect("entered_intersection", self, "_on_Map_entered_intersection") != OK:
			printerr(map, "在连接 entered_intersection 信号时出现错误")
	
	# 添加地图按钮
	var to = $CanvasLayer/Buttons
	var size = 60
	for p in n_gene_data.get_map_pos_list():
		var button = Button.new()
		button.rect_position = p * size
		button.rect_size = Vector2(size, size)
		button_list[p] = button
		button.text = str(p)
		if button.connect("pressed", self, "_on_Button_pressed", [map_data[p], p]) != OK:
			print(button, "连接信号时出现错误")
		to.add_child(button)
	
	# 设置到第一个地图中
	$Player.position = map_data[Vector2(0,0)].position + Vector2(200, 200)



func _input(event):
	if event is InputEventMouseButton:
		if event.doubleclick:
			# 双击重新加载当前场景
			get_tree().reload_current_scene()



## 进入地图后
var button_list = {}
var last_button : Button
func _on_Map_entered_map(map : Map, mini_pos: Vector2):
	# 设置相机镜头为这个地图区域
	$Player/MapCamera.set_map(map)
	
	# 设置当前这个区域的按钮的颜色为红色
	if last_button:
		last_button.modulate = Color.white
	last_button = button_list[mini_pos]
	last_button.modulate = Color.red


func _on_Map_entered_intersection(next_map: Map, pos: Vector2):
	# 进入到路口则跳转到对应位置
	$Player.global_position = pos


func _on_Button_pressed(map: Map, pos: Vector2):
	# 点击按钮，跳转到这个位置
	$Player/MapCamera.set_map(map)
	$Player.global_position = map.get_map_center_pos() + Vector2(0, -128)


